//
//  Heart24ViewModel.swift
//  MoyoungHome
//
//  Created by 易先生 on 2022/9/20.
//

import UIKit
import RxSwift
import RxCocoa
import MYModule

open class HeartRateProvider: NSObject {

    public var date: Date
    
	public let curDayChart = BehaviorRelay<HeartRateChartDataModel?>(value: nil)

	public let weekChart = BehaviorRelay<HeartRateChartDataModel?>(value: nil)

	public let monthChart = BehaviorRelay<HeartRateChartDataModel?>(value: nil)
    
	public let heartRateZoneRelay = BehaviorRelay<HeartRateZoneModel>(value: HeartRateZoneModel())
    
      
    public init(date: Date) {
        self.date = date
		super.init()
        
        addNotifation()
        
        updateData()
        
        updateTimingHeartDate()
	}
    
    
    func addNotifation() {
        
        /// 进入前台通知,延时一秒是因为给SDK setTime 留时间
        NotificationCenter.default.rx.notification(UIApplication.willEnterForegroundNotification).take(until: self.rx.deallocated).delay(.seconds(1), scheduler: MainScheduler()).subscribe(onNext: {[weak self] noti in
            
            guard let self = self else { return }
            let nowTime = Date().timeIntervalSince1970
            let time = self.date.timeIntervalSince1970
            // 半小时时差,就需要更新
            if abs(nowTime - time) >= 1800 {
                self.updateData()
            }
            
        }).disposed(by: rx.disposeBag)
        
        
        NotificationCenter.default.rx.notification(.kUpdateUINotification).take(until: self.rx.deallocated).subscribe(onNext: {[weak self] _ in
            
            self?.updateData()
            
        }).disposed(by: rx.disposeBag)
        
    }
    

	public func updateData() {
        
		getDayDatas()
		getWeekDatas()
        getMonthDatas()
        
    }
    
    public func updateTimingHeartDate() {
        
        if !date.isToday {
            return
            
        }
        
        // 15天睡眠历史记录
        BluetoothManager.shared.getSleepDatas(of: self.date, backward: 15, forcedUpdate: false) {[weak self] in
            
            self?.updateData()
            
        }
        
        BluetoothManager.shared.getTimingHeartRates(of: self.date, backward: 15, forcedUpdate: false) {[weak self] in
            
            self?.updateData()
            
            
        }
        
    }
    
    
	public func getDayDatas() {

        let model = HeartRateChartDataModel(date: date)
        self.curDayChart.accept(model)
        
        // 心率区间
        let heartRateZoneModel = heartDataAnalysis(date: date)
        heartRateZoneRelay.accept(heartRateZoneModel)
    }

    private func heartDataAnalysis(date: Date) ->HeartRateZoneModel {
        
        guard let heartModel = HeartRateModel.day(date: date) else {
            return HeartRateZoneModel()
        }

        // 日常心率区间
        let heartRateZoneModel = HeartRateZoneModel.calculationMinute(with: heartModel.hearts, heartRateInterval: 30, componet: .minute)
        
		return heartRateZoneModel
	}

	public func getWeekDatas() {

        let weekHearts = HeartRateModel.weekDay(date: date)
		let weekModel = HeartRateChartDataModel(date: date, heartRateModels: weekHearts)
        
		weekChart.accept(weekModel)
	}

	public func getMonthDatas() {

        let monthHearts = HeartRateModel.month(date: date)
        let monthModel = HeartRateChartDataModel(date: date, heartRateModels: monthHearts)
        
		monthChart.accept(monthModel)
	}


//	private lazy var format: DateFormatter = {
//		let format = DateFormatter()
//		format.calendar = Calendar.init(identifier: .gregorian)
//		format.dateFormat = "HH:mm"
//		return format
//	}()
    
    
}
